<?php
/**
 * Created by PhpStorm.
 * User: 1
 * Date: 2017-05-03
 * Time: 15:14
 */

namespace app\src\sunsun\heatingRod\action;


use app\src\base\action\BaseAction;
use app\src\base\helper\ResultHelper;
use app\src\sunsun\heatingRod\logic\HeatingRodTempHourHisLogic;

class HeatingRodTempHisAction extends BaseAction
{
    public function clearExpiredData($dataTimestamp)
    {
        $map['create_time'] = ['lt', $dataTimestamp];
        $result = (new HeatingRodTempHourHisLogic())->delete($map);
        return $result;
    }

    /**
     * 增加一条温度值记录
     * @param $did
     * @param $content
     * @param $item
     * @return array
     * @internal param $data
     * @internal param $did
     */
    public function add($did, $content, $item)
    {

        $entity = [];
        //实时温度数据
        if (array_key_exists("t", $content)) {
            $t = intval($content['t']);
        } else {
            return ResultHelper::error('缺少t值');
        }

        if ($t <= 0) {
            return ResultHelper::error('t值错误');
        }
        $entity['did'] = $did;
        $entity['temp'] = $t;
        $entity['create_time'] = $item['create_time'];
        $entity['ymd'] = date('Ymd', $item['create_time']);
        $entity['ymdh'] = date('YmdH', $item['create_time']);

        // 只记录时段的
        $tempHourLogic = new HeatingRodTempHourHisLogic();
        $map['did'] = $did;
        $map['ymd'] = $entity['ymd'];
        $map['ymdh'] = $entity['ymdh'];
        $result = $tempHourLogic->getInfo($map);
        if ($result['status'] && is_array($result['info'])) {
            $temp = $result['info']['temp'];
            $temp = ($t + $temp) / 2;
            $result = $tempHourLogic->save($map, ['temp' => $temp, 'update_time' => time()]);
        } else {
            $entity['update_time'] = time();
            $result = $tempHourLogic->add($entity);
            unset($entity['update_time']);
        }

        return $this->result($result);
    }
}